/**
 * 
 */
package core.internal;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import util.Logger;

import core.internal.builder.file.FileSystemBuilder;
import core.internal.strategy.FileFilter;

/**
 * @author cipri
 *
 */
public class InternalStructure
{
    private SystemItem _root;
    private FileFilter _filter;
    private String _path;
    private String _f;
    
    public InternalStructure(String path) throws FileNotFoundException
    {
        FileSystemBuilder builder = new FileSystemBuilder();
        builder.parseDirectory(new File(path));
        _root = builder.getRoot();
        _filter = new FileFilter();
    }
    
    public void writeArchive(String path, String filter)
    {
        //Aici urmeaza sa se creeze arhiva
        Logger.logln("Arhiva creata: " + path);
        _path = path;
        _f = filter;
        archiveItem(_root);
    }
    
    public void writeFiles(String path, String filter)
    {
        //Aici urmeaza sa se creeze imaginea
        Logger.logln("Imagine creata: " + path);
        _path = path;
        _f = filter;
        writeItem(_root);
    }
    
    private void writeItem(SystemItem item)
    {
        String oldPath = _path;
        File file = new File(_path + item.getName());
        if (item.isDirectory())
        {
            file.mkdir();
            _path.concat(item.getName());
            for (int i = 0; i < item.getChilds().size(); i++)
            {
                writeItem(item.getChilds().get(i));    
            }
            _path = oldPath;
        }
        else 
        {
            try
            {
                if (_filter.applyFiler(item.getName(), _f))
                {
                    file.createNewFile();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    private void archiveItem(SystemItem item)
    {
        String oldPath = _path;
        File file = new File(_path + item.getName());
        
        if (item == _root)
        {
            file = new File(_path + item.getName() + ".sam");   
        }
        
        if (item.isDirectory())
        {
            file.mkdir();
            _path.concat(item.getName());
            for (int i = 0; i < item.getChilds().size(); i++)
            {
                writeItem(item.getChilds().get(i));    
            }
            _path = oldPath;
        }
        else 
        {
            try
            {
                if (_filter.applyFiler(item.getName(), _f))
                {
                    file.createNewFile();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    public void print()
    {
        _root.print();
    }
}
